<%@page import="multiface.awwadco.jpa.News"%>
<%@page import="multiface.awwadco.jpa.File"%>
<%@page import="multiface.awwadco.jpa.PersistenceManager"%>
<%@page import="multiface.web.util.categories.AlberoCategorieProdotti"%>
<%@page import="java.util.LinkedList"%>
<%@page import="javax.persistence.Query"%>
<%@page import="multiface.web.util.Paginator"%>
<%@page import="java.util.Iterator"%>
<%@page import="multiface.awwadco.jpa.Prodotto"%>
<%@page import="multiface.awwadco.jpa.Categoria"%>
<%@page import="java.util.List"%>
<%@page import="javax.persistence.EntityManager"%>
<%@page import="javax.persistence.Persistence"%>
<%@page import="javax.persistence.EntityManagerFactory"%>
<%

    EntityManagerFactory emf = PersistenceManager.getInstance().getEntityManagerFactory();
    EntityManager em = emf.createEntityManager();

    if (((Long) em.createNativeQuery("SELECT Count(*) FROM news").getSingleResult()) > 0) {

        //Parametri della jsp
        //String order = request.getParameter("order");
        //String direction = request.getParameter("direction");
        String jsp = "news_month.jsp";
        String functionJS = "open";
        String indexs = request.getParameter("index");
        int index = 0;
        String year = request.getParameter("year");
        String month = request.getParameter("month");

        //Controlli sui parametri
        if (indexs != null) {
            index = Integer.parseInt(indexs);
        }


        //Paginator
        Paginator paginator = new Paginator();
        paginator.setCSSClass("pager-list");
        paginator.setCSSClassCurrentPage("selected");
        paginator.setCurrentIndex(index);
        paginator.setElementsForPage_fromDB(false);
        paginator.setFunctionJS(functionJS);
        paginator.setPageReturn(jsp);

        //Set Parametri iniziali
        paginator.addParameter("index", index + "");
        paginator.addParameter("year", year);
        paginator.addParameter("month", month);

        List<News> list = new LinkedList<News>();

        Query q = em.createNativeQuery("SELECT p.* FROM news p WHERE YEAR(p.dataora)=? AND MONTH(p.dataora)=? ORDER BY p.dataora DESC", News.class);
        q.setParameter(1, year);
        q.setParameter(2, month);
        paginator.setTotalElements(q.getResultList().size());
        q.setFirstResult(index);
        q.setMaxResults(paginator.getElementsForPage());
        list = q.getResultList();

        //out.print(paginator);


        Iterator i = list.iterator();
        while (i.hasNext()) {
            News p = (News) i.next();
%>

<div class="news">
    <div class="title"><%=p.getTitolo()%><div class="info"><%=p.getUtenteIdutente().getUser()%> - <%=p.getDataora().toString().substring(0, 16)%></div></div>
    <div class="desc"><%=p.getTesto()%></div>
</div>
<div style="clear: none;"></div>
<%


        }

        out.print(paginator);
    }
    em.close();
    //emf.close();
%>

